package com.cgx.service.impl;

import com.cgx.dao.CategoryDao;
import com.cgx.entity.Category;
import com.cgx.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chenguanxin
 * @date 2020-07-22 21:17
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Override
    public List<Category> initTree() {
        List<Category> treeData = categoryDao.findAllByDelFlagOrderByPriority(0);
        List<Category> menuList = new ArrayList<>();
        for (int i = 0; i < treeData.size(); i++) {
            if (treeData.get(i).getParentId().equals("0")) {
                menuList.add(treeData.get(i));
            }
        }
        for (Category menu : menuList) {
            menu.setChildren(getChild(menu.getId(), treeData));
        }
        return menuList;
    }

    // 递归查询子菜单
    private static List<Category> getChild(String id, List<Category> rootMenu) {
        List<Category> childList = new ArrayList<>();
        for (Category menu : rootMenu) {
            if (menu.getParentId().equals(id)) {
                childList.add(menu);
            }
        }
        for (Category menu : childList) {
            menu.setChildren(getChild(menu.getId(), rootMenu));
        }
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }
}
